<?php
defined('BASEPATH') or exit('No direct script access allowed!');

class MTask extends CI_Model {
  function __construct() {
    parent::__construct();
    $this->load->library('elfSecurity');
    $this->load->database();
  }

  function add($projectHash, $parentHash, $name, $tagColor, $createdBy, $detail, $root = null) {
    do {
      $hash = $this->elfsecurity->randStr(15);
      $result = $this->db->where('hash', $hash)->get('task')->row();
    } while (!empty($result));
    if(!empty($root)) {
      $parent = new stdClass();
      $parent->right = 1;
      $parent->hash = '-1';
      $parent->depth = 0;
      $hide = true;
      $hash = '0';
    } else {
      $parent = $this->get($parentHash);
      if(empty($parent)) return false;
      $this->db->query('UPDATE task SET `right`=`right`+2 WHERE `projectHash`=\''.$projectHash.'\' AND `right`>='.$parent->right);
      $this->db->query('UPDATE task SET `left`=`left`+2 WHERE `projectHash`=\''.$projectHash.'\' AND `left`>='.$parent->right);
    }
    $this->db->insert('task', array(
      'hash' => $hash,
      'projectHash' => $projectHash,
      'left' => $parent->right,
      'right' => $parent->right + 1,
      'parentHash' => $parent->hash,
      'depth' => $parent->depth + 1,
      'hide' => empty($hide) ? false : $hide,
      'finished' => false,
      'name' => $name,
      'tagColor' => $tagColor,
      'createdTime' => date('Y-m-d H:i:s'),
      'createdBy' => $createdBy,
      'detail' => $detail
    ));
    return $this->get($hash);
  }

  function update($hash, $array) {
    $this->db->where('hash', $hash)->update('task', $array);
    return $this->get($hash);
  }

  function get($hash) {
    return $this->db->where('hash', $hash)->get('task')->row();
  }

  function getById($id) {
    return $this->db->where('id', $id)->get('task')->row();
  }

  function delete($projHash, $hash) {
    $record = $this->get($hash);
    if(empty($record)) return true;
    $this->db->where('hash', $hash)->delete('task');
    $this->db->query('UPDATE task SET `right`=`right`-2 WHERE `projectHash`=\''.$projectHash.'\' AND `right`>='.$record->right);
    $this->db->query('UPDATE task SET `left`=`left`-2 WHERE `projectHash`=\''.$projectHash.'\' AND `left`>='.$record->right);
    $this->load->model('MComment', 'mcomment');
    $this->mcomment->deleteAll($hash);
    return true;
  }

  function getAll($projectHash) {
    return $this->db->where('projectHash', $projectHash)->order_by('left', 'ASC')->get('task')->result();
  }
}
